<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <el-form :inline="true">
        <div style="display:inline-block;font-size:15px;">医院名称：</div>
        <el-input
          @keyup.enter.native="handleFilter"
          clearable
          v-model="listQuery.hospitalName"
          style="width: 200px;margin-right:15px;margin-top:7px"
          class="filter-item"
          placeholder="请输入医院名称"
        ></el-input>
        <div style="display:inline-block;font-size:15px;">医院详细地址：</div>
        <el-input
          @keyup.enter.native="handleFilter"
          clearable
          v-model="listQuery.hospitalAddress"
          style="width: 200px;margin-right:15px;margin-top:7px"
          class="filter-item"
          placeholder="请输入医院详细地址"
        ></el-input>
        <div style="display:inline-block;font-size:15px;">科室：</div>
        <el-input
          @keyup.enter.native="handleFilter"
          clearable
          v-model="listQuery.departmentName"
          style="width: 200px;margin-right:15px;margin-top:7px"
          class="filter-item"
          placeholder="请输入科室"
        ></el-input>
        <div style="display:inline-block;font-size:15px;">病房号：</div>
        <el-input
          @keyup.enter.native="handleFilter"
          clearable
          v-model="listQuery.wardName"
          style="width: 200px;margin-right:15px;margin-top:7px"
          class="filter-item"
          placeholder="请输入病房号"
        ></el-input>
        <div style="display:inline-block;font-size:15px;">设备编号：</div>
        <el-input
          @keyup.enter.native="handleFilter"
          clearable
          v-model="listQuery.equipmentNumber"
          style="width: 200px;margin-right:15px;margin-top:7px"
          class="filter-item"
          placeholder="请输入设备编号"
        ></el-input>
        <el-button
          class="filter-item"
          type="primary"
          v-waves
          icon="el-icon-search"
          @click="handleFilter"
          style="margin-top:7px;"
        >搜索</el-button>
        <el-button
          type="primary"
          class="filter-item"
          @click="handleDownload"
          icon="el-icon-download"
          :loading="downloadLoading"
          style="margin-top:7px;"
        >批量导出</el-button>
        <el-button
          type="primary"
          v-waves
          icon="el-icon-circle-plus-outline"
          class="filter-item"
          @click="add1"
          style="margin-top:7px;"
        >新增</el-button>
        <el-button
          type="primary"
          v-waves
          icon="el-icon-circle-plus-outline"
          class="filter-item"
          style="margin-top:7px;"
          @click="uploadBtn"
        >批量绑定</el-button>
        <el-button
          type="primary"
          v-waves
          icon="el-icon-circle-plus-outline"
          class="filter-item"
          style="margin-top:7px;"
          @click="bindEqBtn1"
        >批量解绑</el-button>
      </el-form>
    </div>
    <!-- table 表格 -->
    <el-table
      :data="list"
      v-loading="loading.list"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column align="center" label="序号" prop="index" width="120px"/>
      <el-table-column align="center" label="医院名称" prop="hospitalName"/>
      <el-table-column align="center" label="医院详细地址" prop="hospitalAddress"/>
      <el-table-column align="center" label="科室" prop="departmentName"/>
      <el-table-column align="center" label="病房号" prop="wardName"/>
      <el-table-column align="center" label="床号" prop="bedName"/>
      <el-table-column align="center" label="床位编号" prop="deptId"/>
      <el-table-column align="center" label="设备编号" prop="equipmentNumber">
        <template slot-scope="scope">
          {{scope.row.equipmentNumber ? scope.row.equipmentNumber : '-'}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width" width="250px">
        <template slot-scope="scope">
          <div class="fx">
            <el-button size="mini" type="danger" @click="del(scope.row.deptId)" v-if="!scope.row.equipmentNumber">删除</el-button>
            <el-button
              size="mini"
              type="primary"
              @click="edit(scope.row)"
            >编辑</el-button>
            <el-button size="mini" style="width:80px;" type="primary" @click="unBindEqBtn(scope.row.equipmentId)" v-if="scope.row.equipmentNumber">解绑设备</el-button>
            <el-button size="mini" style="width:80px;" type="primary" @click="bindEqBtn(scope.row.deptId)" v-else>绑定设备</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.offset"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 添加床位和编辑床位弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialog.add" width="500px">
      <el-form
        :model="addQuery"
        :rules="addRules"
        ref="addDept"
        label-position="right"
        label-width="120px"
      >
        <el-form-item label="医院" prop="hospital">
          <el-select v-model="addQuery.hospitalId" placeholder="请选择" style="width:220px;" :disabled="dialogType !== 1"
              @change="getDeptNameList">
            <el-option
              v-for="item in hospitalList"
              :key="item.hospitalId"
              :label="item.hospitalName"
              :value="item.hospitalId"
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科室" prop="kdeptName">
          <el-select v-model="addQuery.kdept" placeholder="请选择" style="width:220px;" :disabled="dialogType !== 1"
              @change="getWardNameList">
            <el-option
              v-for="item in deptNameList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="病房" prop="wdeptName">
          <el-select v-model="addQuery.deptId" placeholder="请选择" style="width:220px;" :disabled="dialogType !== 1"
            @change="getWardName">
            <el-option
              v-for="item in wardNameList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="床位" prop="bdeptName">
          <el-input v-model="addQuery.deptName" placeholder="请输入床位" style="width:220px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loading.add" @click="setDate">确定</el-button>
        <el-button type="primary" @click="dialog.add = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 绑定设备 弹框 -->
    <el-dialog title="绑定设备" :visible.sync="dialog.bindEq" width="500px">
      <el-form
        :model="bindEqQuery"
        :rules="addRules"
        ref="addDept"
        label-position="right"
        label-width="120px"
      >
        <el-form-item label="设备编号" prop="equipmentNumber">
          <el-input v-model="bindEqQuery.equipmentNumber" placeholder="请输入设备编号" style="width:220px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="bindingEquipment">确定</el-button>
        <el-button type="primary" @click="dialog.bindEq = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 导入excel -->
    <input type="file" @change="uploadExcel" ref='uploadExcel' style="display:none">
  </div>
</template>

<script>
import { 
  getPartList, 
  setPart,
  dropDownHospitalList,
  delPart,
  dropDownPartList,
  bindingEquipment, 
  unBindingEquipment,
  bindingBatchEquipment
} from "@/api/hospital";
import { parseTime } from "@/utils";
export default {
  name: "hospital_ward",
  data() {
    return {
      total: 0,
      listQuery: {
        offset: 1,
        limit: 10,
        hospitalId: "",
        hospitalName: "",
        hospitalAddress: "",
        departmentName: "",
        wardName: "",
        bedName: "",
        equipmentNumber: "",
        deptName: "",
        type: 3
      },
      dialog: {
        add: false,
        bindEq:false
      },
      loading: {
        list: false
      },
      list: null,
      dialogType: 1,
      addQuery: {
        hospitalId:"",
        deptName: "",
        deptType: 3,
        fid: "",
        deptId:"",
        kdept:""
      },
      addRules: {
        deptName: [{ required: true, message: "请输入病房", trigger: "blur" }]
      },
      deptId: "",
      hospitalId:"",
      hospitalList:[],
      downloadLoading:false,
      getDeptQuery:{
        deptType:1,
        hospitalId:''
      },
      getWardQuery:{
        deptType:2,
        hospitalId:''
      },
      deptNameList:[],
      wardNameList:[],
      bindEqQuery:{
        deptId:'',
        equipmentNumber:''
      },
      selectOptions:[],
      unBindEq:[]
    };
  },
  created() {
    this.getPartList();
  },
  computed: {
    dialogTitle() {
      return this.dialogType === 1 ? "新增床位" : "编辑床位";
    }
  },
  methods: {
    // 多选
    handleSelectionChange(val) {
      this.selectOptions = val;
    },
    
    // 绑定设备
    async bindEqBtn(deptId){
      this.bindEqQuery.deptId = deptId
      this.bindEqQuery.equipmentNumber= ''
      this.dialog.bindEq = true
    },
    async bindingEquipment(){
      const data = await bindingEquipment(this.bindEqQuery)
      if(data.code == 1){
        this.$message({
          type: "success",
          message: "绑定成功!"
        });
        this.dialog.bindEq = false
        this.getPartList()
      }
    },
    // 解绑设备
    async unBindEqBtn(equipmentId){
      this.unBindEq = []
      this.unBindEq.push(equipmentId)
      this.unBindingEquipment()
    },
    
    // 解绑设备(多选)
    async bindEqBtn1(){
      this.unBindEq = []
      if(this.selectOptions.length==0){
        this.$message({
          type: "error",
          message: "请先选择需要解绑的床位！"
        });
      }else{
        this.selectOptions.forEach(value => {
          this.unBindEq.push(value.equipmentId)
        })
        this.unBindingEquipment()
      }
    },

    // 解绑设备
    async unBindingEquipment(){
      this.$confirm('是否解绑设备?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const data = await unBindingEquipment({
            equipmentId:this.unBindEq
          })
          if(data.code == 1){
            this.$message({
              type: "success",
              message: "解绑成功!"
            });
            this.getPartList()
          }
        }).catch(() => {

        });
    },
    // 获取医院下拉列表
    async getHospiltalList(){
      const { data } = await dropDownHospitalList()
      this.hospitalList = data
    },
    // 获取科室下拉列表
    async getDeptNameList(){
      // this.addQuery.kdept = ''
      // this.addQuery.deptId = ''
      // this.addQuery.deptName = ''
      this.getDeptQuery.hospitalId = this.addQuery.hospitalId
      const { data } = await dropDownPartList(this.getDeptQuery)
      this.deptNameList = data
    },
    // 获取病房下拉列表
    async getWardNameList(){
      // this.addQuery.deptId = ''
      // this.addQuery.deptName = ''
      this.getWardQuery.hospitalId = this.addQuery.hospitalId
      this.getWardQuery.deptFid = this.addQuery.kdept
      const { data } = await dropDownPartList(this.getWardQuery)
      this.wardNameList = data
    },
    //
    getWardName(){
      // this.addQuery.deptName = ''
      // console.log("床位：",this.addQuery.deptId);
    },
    //导出
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["医院名称", "医院详细地址","科室", "病房号","床位号","床位编号","设备编号"];
        const filterVal = ["hospitalName", "hospitalAddress", "departmentName","wardName","bedName","deptId","equipmentNumber"];
        const data = this.formatJson(filterVal, this.list);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "床位列表"
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if(j === "ruleType"){
            return v[j] == 1 ? '按小时计费' : v[j] == 2 ? '按时间段计费' : '按日套餐计费'
          }else{
            return v[j];
          }
        })
      );
    },
    uploadBtn () {
      this.$refs.uploadExcel.click()
    },
    //导入
    async uploadExcel (e) {
      try {
        const excel = e.target.files[0]
        const fd = new FormData()
        fd.append('file', excel)
        const res = await bindingBatchEquipment(fd)
        // console.log(res.data);
        if (res.code == 1) {
          this.$message.success('批量绑定设备成功,导入数据'+res.data.size)
          this.getPartList()
        }else{
          this.$message.success(res.data.msg)
        }
      } catch (error) {
        this.$refs.uploadExcel.value = ''
      }
      this.$refs.uploadExcel.value = ''
    },
    //获取病房列表
    async getPartList() {
      this.loading.list = true;
      const { data } = await getPartList(this.listQuery);
      this.list = data.records.map((item, index) => ({
        index: index + 1,
        ...item
      }));
      this.total = data.total;
      this.loading.list = false;
    },
    //点击新增
    add1() {
      this.dialogType = 1;
      this.getHospiltalList().then(() => {
        this.dialog.add = true;
        this.addQuery = {
          deptName: "",
          deptType: 3,
          fid: ""
        };
      })
    },
    // 点击编辑
    edit({departmentName, deptId, hospitalName, wardName, bedName,hospitalId,deptFid}) {
        this.dialog.add = true;
        this.dialogType = 2;
        this.deptId = deptId;
        this.addQuery.hospitalId = hospitalName
        this.addQuery.kdept = departmentName
        this.addQuery.deptId = wardName
        this.addQuery.deptName = bedName
        this.addQuery.deptFid = deptFid
        this.hospitalId = hospitalId
        this.deptId = deptId
    },
    //点击删除
    async del(deptId) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const data = await delPart({ deptId });
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.getPartList();
        })
        .catch(() => {});
    },
    //提交新增
    // async add2() {
    //   this.$refs["addDept"].validate(async valid => {
    //     if (valid) {
    //       this.loading.add = true;
    //       try {
    //         const data = await addDept(this.addQuery);
    //         if (data.code == 1) {
    //           this.$message.success("添加病房成功");
    //           this.dialog.add = false;
    //           this.$refs["addDept"].resetFields();
    //           this.getPartList();
    //         }
    //       } catch (error) {}
    //       this.loading.add = false;
    //     }
    //   });
    // },
    //提交编辑
    async setDate() {
      this.$refs["addDept"].validate(async valid => {
        if (valid) {
          this.loading.add = true;
          console.log("object++++++++",{
            deptType: 3,
            hospitalId: this.dialogType == 2 ? this.hospitalId : this.addQuery.hospitalId,
            deptName:this.addQuery.deptName,
            deptFid:this.dialogType == 2 ? this.addQuery.deptFid : this.addQuery.deptId,
            deptId:this.dialogType == 2 ? this.deptId : ''
          });
          const data = await setPart({
            deptType: 3,
            hospitalId: this.dialogType == 2 ? this.hospitalId : this.addQuery.hospitalId,
            deptName:this.addQuery.deptName,
            deptFid:this.dialogType == 2 ? this.addQuery.deptFid : this.addQuery.deptId,
            deptId:this.dialogType == 2 ? this.deptId : ''
          });
          if (data.code == 1) {
            this.$message.success("操作成功");
            this.dialog.add = false;
            this.$refs["addDept"].resetFields();
            this.getPartList();
          }
          this.loading.add = false;
          this.addQuery.hospitalName = ''
        }
      });
    },
    handleFilter() {
      this.listQuery.offset = 1;
      this.getPartList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getPartList();
    },
    handleCurrentChange(val) {
      this.listQuery.offset = val;
      this.getPartList();
    }
  },
  onShow() {
  }
};
</script>
